﻿using HandyControl.Controls;
using HandyControl.Data;
using log4net;
using PlaceOrder_Core.Services.Interfaces;
using PlaceOrder_Client.Events;
using PlaceOrder_Client.Extensions;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Prism.Services.Dialogs;
using DialogResult = Prism.Services.Dialogs.DialogResult;
using PlaceOrder_Client.Views;
using System.Collections.ObjectModel;
using PlaceOrder_Client.Models.Common;
using Prism.Commands;
using DevExpress.Xpf.WindowsUI.Navigation;
using ImTools;
using PlaceOrder_Core.Services.Instances;
using System.Windows;
using Prism.DryIoc;
using Window = System.Windows.Window;
using Application = System.Windows.Application;
using PlaceOrder_Client.Models.Config;
using PlaceOrder_Core.Helper;
using MessageBox = HandyControl.Controls.MessageBox;
using Newtonsoft.Json;
using System.IO;
using DevExpress.Utils.Filtering.Internal;
using System.Windows.Threading;
using DevExpress.XtraSpellChecker.Parser;
using PlaceOrder_Client.Updater;
using PlaceOrder_Shared.Models.Daily;
using PlaceOrder_Core.PlaceOrderModels;
using DevExpress.Xpf.Charts;
using DevExpress.Mvvm;

namespace PlaceOrder_Client.ViewModels
{
    internal class MainViewModel : Prism.Mvvm.BindableBase, IConfigureService
    {
        private readonly ILog _logger;
        private readonly IRegionManager _regionManager;
        private readonly Prism.Services.Dialogs.IDialogService _dialogService;
        private readonly IUserHelper _userHelper;
        private readonly IData _data;

        public static string ConfigFilePath = "PlaceOrderViewConfig.json";

        public event Action<IDialogResult> RequestClose;

        private string title;

        public string Title
        {
            get { return title; }
            set { title = value; RaisePropertyChanged(); }
        }

        
        public Prism.Commands.DelegateCommand<MenuBar> NavigateCommand { get; private set; }
        public Prism.Commands.DelegateCommand<string> CreateViewCommand { get; private set; } 
        public Prism.Commands.DelegateCommand SaveLocationConfigCommand { get; private set; }
        public Prism.Commands.DelegateCommand SaveConfigCommand { get; private set; } // lxw 0830 加
        
        public Prism.Commands.DelegateCommand<string> QiangPingCommand { get; private set; }

        private async void Init()
        {
            
            await InitializeAsync();
        }

        private async Task InitializeAsync()
        {
           

        }
        private readonly IDailyData _dailyData;
        public MainViewModel(IUserHelper userHelper, IEventAggregator aggregator, IRegionManager regionManager, Prism.Services.Dialogs.IDialogService dialogService,IDailyData dailyData)
        {
            //注册提示消息
            _dailyData = dailyData;
            _userHelper = userHelper;
            _dialogService = dialogService;
            this._regionManager = regionManager;
            Init();
            CreateMenuBar();
           
            NavigateCommand = new Prism.Commands.DelegateCommand<MenuBar>(Navigate);
            CreateViewCommand = new Prism.Commands.DelegateCommand<string>(CreateView);
            SaveLocationConfigCommand = new Prism.Commands.DelegateCommand(SaveLocationConfig); // 旧实现（不包括下单配置）
            SaveConfigCommand = new Prism.Commands.DelegateCommand(SaveConfig);//新实现（包括下单配置）
            aggregator.GetEvent<MessageEvent>().Subscribe(async arg =>
            {

                //Growl.SuccessGlobal("11111",);
                await Task.Delay(10000);
                Growl.Info(arg.Message, "SuccessMsg");

          
            });


            // 创建一个 DispatcherTimer
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(25); // 设置延迟时间为20秒
            timer.Tick += (s,e)=>
            {
                // 停止计时器
                timer.Stop();

                // 在10秒后更新标题
                this.Title = "全益订单管理客户端 - " + UserHelper.NickName;

              
            };
            timer.Start();
            QiangPingCommand = new Prism.Commands.DelegateCommand<string>(QiangPingHandle);
            Title = "全益订单管理客户端 - " + UserHelper.NickName;

            Messenger.Default.Register<string>(this, "CheckIfChatWindowOpened", async (obj) => await HandleCheckIfChatWindowOpened(obj));

        }

        private object CheckMessageOpenLock  = new object();
        private async Task HandleCheckIfChatWindowOpened(string obj)
        {
           
           await CreateChatMessageViewAsync();
            
        }

        private void QiangPingHandle(string status)
        {
            switch(status)
            {
                case "Normal":
                    OrderListViewModel.ShowQiangPing();
                    break;
                case "CountDown":
                    OrderListViewModel.ShowQiangPingCountDownFiveMinutes(60*5);
                    break;
                default: break;
            }
            
        }
        public static void SaveConfig()
        {
            try
            {
                // 读取现有配置
                WindowConfig existingConfig = null;
                if (File.Exists(ConfigFilePath))
                {
                    string existingJson = File.ReadAllText(ConfigFilePath);
                    existingConfig = JsonConvert.DeserializeObject<WindowConfig>(existingJson);
                }

                // 如果没有现有配置，则初始化一个新的配置对象
                if (existingConfig == null)
                {
                    existingConfig = new WindowConfig
                    {
                        WindowPositions = new Dictionary<string, List<WindowPosition>>()
                    };
                }

                // 创建新的窗口位置列表
                var longhuWindowPositions = new List<WindowPosition>();
                var mainWindowPositions = new List<WindowPosition>();
                var onHoldWindowPositions = new List<WindowPosition>();
                var chatWindowPositions = new List<WindowPosition>();

                foreach (Window window in Application.Current.Windows)
                {
                    if (window is LongHuView longhuView)
                    {
                        longhuWindowPositions.Add(new WindowPosition
                        {
                            Top = longhuView.Top,
                            Left = longhuView.Left,
                            Width = longhuView.ActualWidth,
                            Height = longhuView.ActualHeight
                        });
                    }

                    if (window is MainView mainView)
                    {
                        mainWindowPositions.Add(new WindowPosition
                        {
                            Top = mainView.Top,
                            Left = mainView.Left,
                            Width = mainView.ActualWidth,
                            Height = mainView.ActualHeight
                        });
                    }

                    if (window is OnHoldPositionsView holdView)
                    {
                        onHoldWindowPositions.Add(new WindowPosition
                        {
                            Top = holdView.Top,
                            Left = holdView.Left,
                            Width = holdView.ActualWidth,
                            Height = holdView.ActualHeight
                        });
                    }

                    if (window is ChatMessageWindow chatView)
                    {
                        chatWindowPositions.Add(new WindowPosition
                        {
                            Top = chatView.Top,
                            Left = chatView.Left,
                            Width = chatView.ActualWidth,
                            Height = chatView.ActualHeight
                        });
                    }
                }

                // 更新窗口位置配置，保留现有的 OrderView 配置
                if (!existingConfig.WindowPositions.ContainsKey("OrderView"))
                {
                    existingConfig.WindowPositions["OrderView"] = new List<WindowPosition>();
                }
                existingConfig.WindowPositions["OrderView"] = new List<WindowPosition>();
                existingConfig.WindowPositions["LongHuView"] = longhuWindowPositions;
                existingConfig.WindowPositions["MainView"] = mainWindowPositions;
                existingConfig.WindowPositions["OnHoldView"] = onHoldWindowPositions;
                existingConfig.WindowPositions["ChatMessageView"] = chatWindowPositions;
                existingConfig.WindowPositions["MainView"] = mainWindowPositions;

                // 将更新后的配置序列化为 JSON 字符串
                string json = JsonConvert.SerializeObject(existingConfig, Formatting.Indented);

                // 保存到文件
                File.WriteAllText(ConfigFilePath, json);

                Messenger.Default.Send("11", "saveOrderViewConfig");
                MessageBox.Show("保存布局成功！");

            }
            catch (Exception ex)
            {
                // 处理异常情况，记录错误日志
                AppLog.WriteError("保存布局失败：" + ex.Message);
                MessageBox.Show("保存布局失败：" + ex.Message);
            }
        }


        public static void SaveLocationConfig()
        {
            try
            {
                // 读取现有配置
                WindowConfig existingConfig = null;
                if (File.Exists(ConfigFilePath))
                {
                    string existingJson = File.ReadAllText(ConfigFilePath);
                    existingConfig = JsonConvert.DeserializeObject<WindowConfig>(existingJson);
                }

                // 如果没有现有配置，则初始化一个新的配置对象
                if (existingConfig == null)
                {
                    existingConfig = new WindowConfig
                    {
                        WindowPositions = new Dictionary<string, List<WindowPosition>>()
                    };
                }

                // 创建新的窗口位置列表
                var longhuWindowPositions = new List<WindowPosition>();
                var mainWindowPositions = new List<WindowPosition>();
                var onHoldWindowPositions = new List<WindowPosition>();
                var chatWindowPositions = new List<WindowPosition>();

                foreach (Window window in Application.Current.Windows)
                {
                    if (window is LongHuView longhuView)
                    {
                        longhuWindowPositions.Add(new WindowPosition
                        {
                            Top = longhuView.Top,
                            Left = longhuView.Left,
                            Width = longhuView.ActualWidth,
                            Height = longhuView.ActualHeight
                        });
                    }

                    if (window is MainView mainView)
                    {
                        mainWindowPositions.Add(new WindowPosition
                        {
                            Top = mainView.Top,
                            Left = mainView.Left,
                            Width = mainView.ActualWidth,
                            Height = mainView.ActualHeight
                        });
                    }

                    if (window is OnHoldPositionsView holdView)
                    {
                        onHoldWindowPositions.Add(new WindowPosition
                        {
                            Top = holdView.Top,
                            Left = holdView.Left,
                            Width = holdView.ActualWidth,
                            Height = holdView.ActualHeight
                        });
                    }

                    if (window is ChatMessageWindow chatView)
                    {
                        chatWindowPositions.Add(new WindowPosition
                        {
                            Top = chatView.Top,
                            Left = chatView.Left,
                            Width = chatView.ActualWidth,
                            Height = chatView.ActualHeight
                        });
                    }
                }

                // 更新窗口位置配置，保留现有的 OrderView 配置
                if (!existingConfig.WindowPositions.ContainsKey("OrderView"))
                {
                    existingConfig.WindowPositions["OrderView"] = new List<WindowPosition>();
                }
                existingConfig.WindowPositions["LongHuView"] = longhuWindowPositions;
                existingConfig.WindowPositions["MainView"] = mainWindowPositions;
                existingConfig.WindowPositions["OnHoldView"] = onHoldWindowPositions;
                existingConfig.WindowPositions["ChatMessageView"] = chatWindowPositions;
                existingConfig.WindowPositions["MainView"] = mainWindowPositions;

                // 将更新后的配置序列化为 JSON 字符串
                string json = JsonConvert.SerializeObject(existingConfig, Formatting.Indented);

                // 保存到文件
                File.WriteAllText(ConfigFilePath, json);

                //// 记录日志和显示成功消息
                //string mainMsg = "保存主窗口布局。";
                //string onHoldMsg = onHoldWindowPositions.Count > 0 ? "，保存持仓布局" : "";
                //string longhuMsg = longhuWindowPositions.Count > 0 ? "保存了龙虎榜布局" : "";
                //string chatMessageMsg = chatWindowPositions.Count > 0 ? "，以及聊天窗口布局" : "";

                //if(onHoldWindowPositions.Count == 0&& longhuWindowPositions.Count == 0&& chatWindowPositions.Count == 0)
                //{
                //    Growl.SuccessGlobal($"保存主窗口布局成功！");
                //}
                //else
                //{
                //    Growl.SuccessGlobal($"{mainMsg}{longhuMsg}{onHoldMsg}{chatMessageMsg}");
                //}
                   
            }
            catch (Exception ex)
            {
                // 处理异常情况，记录错误日志
                AppLog.WriteError("保存布局失败：" + ex.Message);
               // MessageBox.Show("保存布局失败：" + ex.Message);
            }
        }



        //private void SaveLocationConfig()
        //{
        //    try
        //    {
        //        List<WindowPosition> orderWindowPositions = new List<WindowPosition>();
        //        List<WindowPosition> longhuWindowPositions = new List<WindowPosition>();
        //        List<WindowPosition> mainWindowPositions = new List<WindowPosition>();
        //        List<WindowPosition> onHoldWindowPositions = new List<WindowPosition>();
        //        List<WindowPosition> chatWindowPositions = new List<WindowPosition>();

        //        foreach (Window window in Application.Current.Windows)
        //        {
        //            // 根据需要排除某些窗口，例如主窗口等
        //            if (window is OrderView myOrderWindow)
        //            {
        //                // 获取窗口位置信息并添加到列表中
        //                orderWindowPositions.Add(new WindowPosition
        //                {
        //                    Top = myOrderWindow.Top,
        //                    Left = myOrderWindow.Left,
        //                    Width = myOrderWindow.ActualWidth,
        //                    Height = myOrderWindow.ActualHeight
        //                });
        //            }

        //            if (window is LongHuView longhuView)
        //            {
        //                // 获取窗口位置信息并添加到列表中
        //                longhuWindowPositions.Add(new WindowPosition
        //                {
        //                    Top = longhuView.Top,
        //                    Left = longhuView.Left,
        //                    Width = longhuView.ActualWidth,
        //                    Height = longhuView.ActualHeight
        //                });
        //            }

        //            if (window is MainView mainView)
        //            {
        //                // 获取窗口位置信息并添加到列表中
        //                mainWindowPositions.Add(new WindowPosition
        //                {
        //                    Top = mainView.Top,
        //                    Left = mainView.Left,
        //                    Width = mainView.ActualWidth,
        //                    Height = mainView.ActualHeight
        //                });
        //            }

        //            if (window is OnHoldPositionsView holdView)
        //            {
        //                // 获取窗口位置信息并添加到列表中
        //                onHoldWindowPositions.Add(new WindowPosition
        //                {
        //                    Top = holdView.Top,
        //                    Left = holdView.Left,
        //                    Width = holdView.ActualWidth,
        //                    Height = holdView.ActualHeight
        //                });
        //            }

        //            if (window is ChatMessageWindow chatView)
        //            {
        //                // 获取窗口位置信息并添加到列表中
        //                chatWindowPositions.Add(new WindowPosition
        //                {
        //                    Top = chatView.Top,
        //                    Left = chatView.Left,
        //                    Width = chatView.ActualWidth,
        //                    Height = chatView.ActualHeight
        //                });
        //            }
        //        }

        //        // 构建保存的数据结构
        //        var windowConfig = new WindowConfig
        //        {
        //            WindowPositions = new Dictionary<string, List<WindowPosition>>
        //    {
        //        { "OrderView", orderWindowPositions },
        //        { "LongHuView", longhuWindowPositions },
        //        { "MainView", mainWindowPositions },

        //        { "OnHoldView", onHoldWindowPositions },
        //        { "ChatMessageView", chatWindowPositions },

        //    }
        //        };

        //        // 将窗口位置列表序列化为 JSON 字符串
        //        string json = JsonConvert.SerializeObject(windowConfig, Formatting.Indented);

        //        // 保存到文件
        //        string filePath = ConfigFilePath;
        //        File.WriteAllText(filePath, json);

        //        // 记录日志和显示成功消息
        //        int orderCount = orderWindowPositions.Count;
        //        int longhuCount = longhuWindowPositions.Count;
        //        string onHoldMsg = onHoldWindowPositions.Count > 0 ? "，保存持仓布局" : "";
        //        string longhuMsg = longhuCount > 0 ? "，保存了龙虎榜布局" : "";
        //        string chatMessageMsg = longhuCount > 0 ? "，以及聊天窗口布局" : "";
        //        AppLog.WriteError($"保存{orderCount}个下单窗口布局成功{longhuMsg}");
        //        MessageBox.Show($"保存{orderCount}个下单窗口布局成功{longhuMsg}{onHoldMsg}{chatMessageMsg}");
        //    }
        //    catch (Exception ex)
        //    {
        //        // 处理异常情况，记录错误日志
        //        AppLog.WriteError("保存布局失败：" + ex.Message);
        //        MessageBox.Show("保存布局失败：" + ex.Message);
        //    }
        //}

        //private void SaveLocationConfig()
        //{
        //    try
        //    {
        //        List<WindowPosition> windowPositions = new List<WindowPosition>();
        //        int Ordercount = 0;
        //        int LonghuCount = 0;
        //        foreach (Window window in Application.Current.Windows)
        //        {
        //            // 根据需要排除某些窗口，例如主窗口等
        //            if (window is OrderView myOrderWindow)
        //            {
        //                // 执行特定的操作，比如获取窗口位置
        //                windowPositions.Add(new WindowPosition
        //                {
        //                    Top = myOrderWindow.Top,
        //                    Left = myOrderWindow.Left,
        //                    Width = myOrderWindow.Width,
        //                    Height = myOrderWindow.Height
        //                });
        //                Ordercount++;
        //            }

        //            if (window is LongHuView longhuView)
        //            {
        //                // 执行特定的操作，比如获取窗口位置
        //                windowPositions.Add(new WindowPosition
        //                {
        //                    Top = longhuView.Top,
        //                    Left = longhuView.Left,
        //                    Width = longhuView.Width,
        //                    Height = longhuView.Height
        //                });
        //                LonghuCount++;
        //            }
        //        }
        //        // 将窗口位置列表序列化为 JSON 字符串
        //        string json = JsonConvert.SerializeObject(new { WindowPositions = windowPositions }, Formatting.Indented);

        //        // 保存到文件
        //        string filePath = "PlaceOrderViewConfig.json"; // 文件路径，可以根据实际情况修改
        //        File.WriteAllText(filePath, json);
        //        string longhuMsg = "";
        //        if(LonghuCount>0)
        //        {
        //            longhuMsg = "，保存了龙虎榜布局";
        //        }
        //        AppLog.WriteError($"保存{Ordercount}个下单窗口布局成功"+longhuMsg);
        //        MessageBox.Show($"保存{Ordercount}个下单窗口布局成功");

        //    }
        //    catch(Exception ex)
        //    {
        //        AppLog.WriteError("保存布局失败" + ex.StackTrace + ex.Message);
        //    }

        //}

        private async void CreateView(string view)
        {
           switch(view)
            {
                case "Order":
                    await CreateOrderViewAsync();
                    break;
                case "LongHu":
                    await CreateLongHuViewAsync();
                    break;


                case "ChatMessage":
                    await CreateChatMessageViewAsync();
                    break;
                case "TradeAmountConfig":
                    await CreateTradeAmountConfigViewAsync();
                    break;
                default:
                    return;
            }
        }

        public async Task CreateChatMessageViewAsync(WindowPosition position = null)
        {
            // 确保所有的 UI 操作在主线程上执行
            await Application.Current.Dispatcher.InvokeAsync(() =>
            {
                if (_chatMessageView == null)
                {
                    // 创建并初始化窗口
                    _chatMessageView = new ChatMessageWindow
                    {
                        Title = $"{UserHelper.NickName}-聊天窗口",
                        // 如果提供了位置参数，则设置窗口位置和大小
                        Left = position?.Left ?? double.NaN,
                        Top = position?.Top ?? double.NaN,
                        Width = position?.Width ?? double.NaN,
                        Height = position?.Height ?? double.NaN,
                        WindowStartupLocation = position == null ? WindowStartupLocation.CenterScreen : WindowStartupLocation.Manual
                    };

                    // 显示窗口
                    _chatMessageView.Show();
                }
                else
                {
                    // 如果窗口已经存在，检查并恢复窗口状态
                    if (_chatMessageView.WindowState == WindowState.Minimized)
                    {
                        // 如果窗口最小化，则先将其恢复正常状态
                        _chatMessageView.WindowState = WindowState.Normal;
                    }

                    // 激活窗口
                    _chatMessageView.Activate();
                }
            });
        }

        //public async Task CreateChatMessageViewAsync(WindowPosition position = null)
        //{
        //    if (_chatMessageView == null)
        //    {
        //        if (position != null)
        //        {
        //            _chatMessageView = new ChatMessageWindow
        //            {
        //                Title = $"{UserHelper.NickName}-聊天窗口",
        //                //WindowStartupLocation = WindowStartupLocation.CenterScreen; // 设置窗口启动位置为屏幕中央
        //                Left = position.Left,
        //                Top = position.Top,
        //                Width = position.Width,
        //                Height = position.Height,
        //            };
        //        }
        //        else
        //        {
        //            _chatMessageView = new ChatMessageWindow
        //            {
        //                Title = $"{UserHelper.NickName}-聊天窗口",
        //                WindowStartupLocation = WindowStartupLocation.CenterScreen // 设置窗口启动位置为屏幕中央
        //            };
        //        }

        //        //await Task.Run(() =>
        //        //{
        //        //    // 模拟一些需要后台执行的初始化操作
        //        //    System.Threading.Thread.Sleep(50); // 模拟延迟
        //        //});


        //        await Application.Current.Dispatcher.InvokeAsync(() =>
        //        {
        //            _chatMessageView.Show();
        //        });
        //    }
        //    else
        //    {
        //        // 如果窗口已经显示，则检查窗口状态
        //        if (_chatMessageView.WindowState == WindowState.Minimized)
        //        {
        //            // 如果窗口最小化，则先将其恢复正常状态
        //            _chatMessageView.WindowState = WindowState.Normal;
        //        }
        //        // 然后再将窗口置顶显示
        //        _chatMessageView.Activate(); // 激活置顶
        //    }
        //}



        public async Task CreateTradeAmountConfigViewAsync(WindowPosition position = null)
        {
            if (_tradeAmountConfigView == null)
            {
                if (position != null)
                {
                    _tradeAmountConfigView = new TradeAmountConfigView
                    {
                        Title = $"{UserHelper.NickName}+交易量配置",
                        //WindowStartupLocation = WindowStartupLocation.CenterScreen; // 设置窗口启动位置为屏幕中央
                        Left = position.Left,
                        Top = position.Top,
                        Width = position.Width,
                        Height = position.Height,
                    };
                }
                else
                {
                    _tradeAmountConfigView = new TradeAmountConfigView
                    {
                        Title = $"{UserHelper.NickName}+交易量配置",
                        WindowStartupLocation = WindowStartupLocation.CenterScreen // 设置窗口启动位置为屏幕中央
                    };
                }

                //await Task.Run(() =>
                //{
                //    // 模拟一些需要后台执行的初始化操作
                //    System.Threading.Thread.Sleep(10); // 模拟延迟
                //});


                await Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    _tradeAmountConfigView.Show();
                });
            }
            else
            {
                // 如果窗口已经显示，则检查窗口状态
                if (_tradeAmountConfigView.WindowState == WindowState.Minimized)
                {
                    // 如果窗口最小化，则先将其恢复正常状态
                    _tradeAmountConfigView.WindowState = WindowState.Normal;
                }
                // 然后再将窗口置顶显示
                _tradeAmountConfigView.Activate(); // 激活置顶
            }
        }
        public static LongHuView _longhuView; // 声明一个私有字段存储单例
        public static OnHoldPositionsView _onHoldView; // 声明一个私有字段存储单例
        public static ChatMessageWindow _chatMessageView; // 声明一个私有字段存储单例
        public static TradeAmountConfigView _tradeAmountConfigView; // 声明一个私有字段存储单例
        public static async Task CreateLongHuViewAsync(WindowPosition position=null)
        {

            if (_longhuView == null)
            {
                if (position != null)
                {
                    _longhuView = new LongHuView
                    {
                        Title = $"{UserHelper.NickName}-中介成交龙虎榜",
                        //WindowStartupLocation = WindowStartupLocation.CenterScreen; // 设置窗口启动位置为屏幕中央
                        Left = position.Left,
                        Top = position.Top,
                        Width = position.Width,
                        Height = position.Height,
                    };
                }
                else
                {
                    _longhuView = new LongHuView
                    {
                        Title = $"{UserHelper.NickName}-中介成交龙虎榜",
                        WindowStartupLocation = WindowStartupLocation.CenterScreen // 设置窗口启动位置为屏幕中央
                    };
                }
                
                //await Task.Run(() =>
                //{
                //    // 模拟一些需要后台执行的初始化操作
                //    System.Threading.Thread.Sleep(10); // 模拟延迟
                //});


                await Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    _longhuView.Show();
                });
            }
            else
            {
                // 如果窗口已经显示，则检查窗口状态
                if (_longhuView.WindowState == WindowState.Minimized)
                {
                    // 如果窗口最小化，则先将其恢复正常状态
                    _longhuView.WindowState = WindowState.Normal;
                }
                // 然后再将窗口置顶显示
                _longhuView.Activate(); // 激活置顶
            }
        }
        private async Task CreateOrderViewAsync()
        {
            var orderWindow = new OrderView
            {
                Title = $"{UserHelper.NickName}+下单窗口",
                WindowStartupLocation = WindowStartupLocation.CenterScreen // 设置窗口启动位置为屏幕中央
            };

            // 使用await确保在UI线程上显示窗口
            await Application.Current.Dispatcher.InvokeAsync(() =>
            {
                orderWindow.Show();
            });
        }

        private async void CreateOrderView()
        {
            var orderWindow = new OrderView
            {
                Title = $"{UserHelper.NickName}+下单窗口",
                WindowStartupLocation = WindowStartupLocation.CenterScreen // 设置窗口启动位置为屏幕中央
            };

            // 使用Task.Run确保长时间的操作在后台线程上执行
            await Application.Current.Dispatcher.InvokeAsync(() =>
            {
                orderWindow.Show();
            });
            //await Task.Run(() =>
            //{
            //    // 模拟一些需要后台执行的初始化操作
            //    System.Threading.Thread.Sleep(100); // 模拟延迟
            //});

        }


        public void Configure()
        {
            //默认导航到IndexView首页
           _regionManager.Regions[PrismRegionManager.MainViewRegionName].RequestNavigate("OrderListView");
        }

        #region 依赖属性
        public ObservableCollection<MenuBar> MenuBars
        {
            get { return menuBars; }
            set { menuBars = value; RaisePropertyChanged(); }
        }
        private ObservableCollection<MenuBar> menuBars;


        void CreateMenuBar()
        {
            MenuBars = new ObservableCollection<MenuBar>();
            MenuBars.Add(new MenuBar() { Icon = "\uE18F", Title = "询价记录", NameSpace = "OrderListView" });
            //MenuBars.Add(new MenuBar() { Icon = "\uE8F2", Title = "聊天列表", NameSpace = "ChatMessageView" });
            MenuBars.Add(new MenuBar() { Icon = "\uE759", Title = "交易复盘", NameSpace = "TransactionReviewView" });
            MenuBars.Add(new MenuBar() { Icon = "\uEC6C", Title = "审核复议", NameSpace = "ChatWorkOrderView" });
            //MenuBars.Add(new MenuBar() { Icon = "\uE95D", Title = "备忘录", NameSpace = "MemoView" });
            //MenuBars.Add(new MenuBar() { Icon = "\uE211", Title = "设置", NameSpace = "SettingsView" });

        }
        #endregion


        /// <summary>
        /// 导航
        /// </summary>
        /// <param name="obj"></param>
        private void Navigate(MenuBar obj)
        {
            if (obj == null || string.IsNullOrWhiteSpace(obj.NameSpace))
                return;
            if(obj.NameSpace== "ChatMessageView")
            {
                Growl.WarningGlobal("聊天界面暂时被禁用，请用下方的窗口");
                return;
            }

            if (obj.NameSpace == "TransactionReviewView")
            {
                Growl.WarningGlobal("交易复盘功能尚在开发中，请等待...");
                //return;
            }
            _regionManager.Regions[PrismRegionManager.MainViewRegionName].RequestNavigate(obj.NameSpace);
        }

        public static async Task CreateOnHoldViewAsync(WindowPosition position = null)
        {

            if (_onHoldView == null)
            {
                if (position != null)
                {
                    _onHoldView = new OnHoldPositionsView
                    {
                        Title = $"{UserHelper.NickName}+持仓信息",
                        //WindowStartupLocation = WindowStartupLocation.CenterScreen; // 设置窗口启动位置为屏幕中央
                        Left = position.Left,
                        Top = position.Top,
                        Width = position.Width,
                        Height = position.Height,
                    };
                }
                else
                {
                    _onHoldView = new OnHoldPositionsView
                    {
                        Title = $"{UserHelper.NickName}+持仓信息",
                        WindowStartupLocation = WindowStartupLocation.CenterScreen // 设置窗口启动位置为屏幕中央
                    };
                }

                //await Task.Run(() =>
                //{
                //    // 模拟一些需要后台执行的初始化操作
                //    System.Threading.Thread.Sleep(50); // 模拟延迟
                //});


                await Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    _onHoldView.Show();
                });
            }
            else
            {
                // 如果窗口已经显示，则检查窗口状态
                if (_onHoldView.WindowState == WindowState.Minimized)
                {
                    // 如果窗口最小化，则先将其恢复正常状态
                    _onHoldView.WindowState = WindowState.Normal;
                }
                // 然后再将窗口置顶显示
                _onHoldView.Activate(); // 激活置顶
            }
        }


        public static async Task ChatMessageViewAsync(WindowPosition position = null)
        {
            if (_chatMessageView == null)
            {
                if (position != null)
                {
                    _chatMessageView = new ChatMessageWindow
                    {
                        Title = $"{UserHelper.NickName}-聊天窗口",
                        //WindowStartupLocation = WindowStartupLocation.CenterScreen; // 设置窗口启动位置为屏幕中央
                        Left = position.Left,
                        Top = position.Top,
                        Width = position.Width,
                        Height = position.Height,
                    };
                }
                else
                {
                    _chatMessageView = new ChatMessageWindow
                    {
                        Title = $"{UserHelper.NickName}-聊天窗口",
                        WindowStartupLocation = WindowStartupLocation.CenterScreen // 设置窗口启动位置为屏幕中央
                    };
                }

                //await Task.Run(() =>
                //{
                //    // 模拟一些需要后台执行的初始化操作
                //    System.Threading.Thread.Sleep(50); // 模拟延迟
                //});


                await Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    _chatMessageView.Show();
                });
            }
            else
            {
                // 如果窗口已经显示，则检查窗口状态
                if (_chatMessageView.WindowState == WindowState.Minimized)
                {
                    // 如果窗口最小化，则先将其恢复正常状态
                    _chatMessageView.WindowState = WindowState.Normal;
                }
                // 然后再将窗口置顶显示
                _chatMessageView.Activate(); // 激活置顶
            }
        }
    }
}
